import javax.swing.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    private ServerSocket serverSocket;
    private JTextArea chatArea;
    private PrintWriter out;

    public ChatServer(int port, JTextArea chatArea) throws IOException {
        this.chatArea = chatArea;
        serverSocket = new ServerSocket(port);
        startListening();
    }

    private void startListening() {
        new Thread(() -> {
            try (ServerSocket ss = serverSocket) {
                while (!ss.isClosed()) {
                    Socket socket = ss.accept();
                    out = new PrintWriter(socket.getOutputStream(), true);
                    handleClient(socket);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void handleClient(Socket socket) {
        new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    String finalInputLine = inputLine;
                    SwingUtilities.invokeLater(() -> chatArea.append("Client: " + finalInputLine + "\n"));
                    // Echo the message back to client
                    out.println(inputLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void send(String msg) {
        if (out != null) {
            out.println(msg);
        }
    }

    public void stop() {
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}